<template>
  <div class="home">
    <div class="buttons-container">
      <button v-for="interval in intervals" :key="interval" @click="changeInterval(interval)">{{ interval }}</button>
    </div>
    <div id="container">
    </div>
  </div>
</template>

<script>
import { createChart } from 'lightweight-charts';

import moment from 'moment';

export default {
  name: 'HomeView',

  data() {
    return {
      intervals: ['1D', '1W', '1M', '1Y'],
      currentInterval: '1D',
      chart: null,
      datasource: null,
      series: null,
      streamingDataProvider: null,
    };
  },

  mounted() {
   
    // 初始化数据
    this.generateData();
    // 初始化图表
    this.init();
    // 设置图表
    this.$nextTick(() => {
      this.setData();
    });

  },
  methods: {
    changeInterval(interval) {
      this.currentInterval = interval;
      this.setData();
    },
    // 初始化图表
    init() {
      //获取容器的高度
      const containerHeight = document.getElementById('container').clientHeight;
      console.log(containerHeight);
      const chartOptions = {
        layout: {
          textColor: 'white',
          background: { type: 'solid', color: 'black' },
        },
        height: containerHeight, //容器的高度
      };
      const container = document.getElementById('container');

      const chart = createChart(container, chartOptions);
      console.log('chart', chart);
      // Only needed within demo page
      // eslint-disable-next-line no-undef
      window.addEventListener('resize', () => {
        chart.applyOptions({ height: containerHeight });
      });

      // 添加蜡烛图
      const series = chart.addCandlestickSeries({
        upColor: '#26a69a',
        downColor: '#ef5350',
        borderVisible: false,
        wickUpColor: '#26a69a',
        wickDownColor: '#ef5350',
      });

      this.series = series;
      const styles = `
          .buttons-container {
              display: flex;
              flex-direction: row;
              gap: 8px;
          }
          .buttons-container button {
              all: initial;
              font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu,
                  sans-serif;
              font-size: 16px;
              font-style: normal;
              font-weight: 510;
              line-height: 24px; /* 150% */
              letter-spacing: -0.32px;
              padding: 8px 24px;
              color: rgba(19, 23, 34, 1);
              background-color: rgba(240, 243, 250, 1);
              border-radius: 8px;
              cursor: pointer;
          }

          .buttons-container button:hover {
              background-color: rgba(224, 227, 235, 1);
          }

          .buttons-container button:active {
              background-color: rgba(209, 212, 220, 1);
          }
      `;

      const stylesElement = document.createElement('style');
      stylesElement.innerHTML = styles;
      container.appendChild(stylesElement);

      const buttonsContainer = document.createElement('div');
      buttonsContainer.classList.add('buttons-container');
      const button = document.createElement('button');
      button.innerText = 'Go to realtime';
      button.addEventListener('click', () => chart.timeScale().scrollToRealTime());
      buttonsContainer.appendChild(button);
      // 添加按钮容器 
      container.appendChild(buttonsContainer);

      // 添加工具提示
      const toolTipWidth = 100;
      const toolTipHeight = 70;
      const toolTipMargin = 15;

      const toolTip = document.createElement('div');
      toolTip.style = `width: ${toolTipWidth}px; height:${toolTipHeight}px; position: absolute; display: none; padding: 15px; box-sizing: border-box; font-size: 12px; text-align: left; z-index: 1000; top: 12px; left: 12px; pointer-events: none; border: 1px solid; border-radius: 2px;font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;`;
      toolTip.style.background = 'black';
      toolTip.style.color = 'white';
      toolTip.style.borderColor = 'rgba( 38, 166, 154, 1)';
      container.appendChild(toolTip);

      // 添加十字光标
      chart.subscribeCrosshairMove(param => {

        if (
          param.point === undefined ||
          !param.time ||
          param.point.x < 0 ||
          param.point.x > container.clientWidth ||
          param.point.y < 0 ||
          param.point.y > container.clientHeight
        ) {
          toolTip.style.display = 'none';
        } else {
          // console.log('鼠标参数', param);

          const dateStr = param.time;
          toolTip.style.display = 'block';
          const data = param.seriesData.get(series);
          const price = data.value !== undefined ? data.value : data.close;
          toolTip.innerHTML = `
              <div style="font-size: 24px; margin: 4px 0px; color: ${'white'}">
              ${Math.round(100 * price) / 100}
              </div>
              <div style="color: ${'white'}">
              ${moment(dateStr * 1000).format('YYYY/MM/DD')} 
              </div>
            `;

          const y = param.point.y;
          let left = param.point.x + toolTipMargin;
          if (left > container.clientWidth - toolTipWidth) {
            left = param.point.x - toolTipMargin - toolTipWidth;
          }

          let top = y + toolTipMargin;
          if (top > container.clientHeight - toolTipHeight) {
            top = y - toolTipHeight - toolTipMargin;
          }
          toolTip.style.left = left + 'px';
          toolTip.style.top = top + 'px';
        }

      });

      // container.appendChild(buttonsContainer);
      // 设置图表的区间
      chart.timeScale().fitContent();

      this.chart = chart;
    },

    // 生成数据函数
    generateData(
      numberOfCandles = 500, // 默认生成500根蜡烛
      updatesPerCandle = 5, // 每根蜡烛的更新次数
      startAt = 100, // 从第100个数据点开始生成实时更新数据
      interval = '1D' // 默认生成1天的数据
    ) {
      console.log('生成数据', numberOfCandles, updatesPerCandle, startAt);
      let randomFactor = 25 + Math.random() * 25; // 生成随机因子
      // 定义一个函数，用于生成样本点的值
      const samplePoint = i =>
        i *
        (0.5 +
          Math.sin(i / 1) * 0.2 +
          Math.sin(i / 2) * 0.4 +
          Math.sin(i / randomFactor) * 0.8 +
          Math.sin(i / 50) * 0.5) +
        200 +
        i * 2;
      // 定义一个函数，用于创建蜡烛图数据
      const createCandle = (val, time) => ({
        time,
        open: val,
        high: val,
        low: val,
        close: val,
      });
      // 定义一个函数，用于更新蜡烛图数据
      const updateCandle = (candle, val) => ({
        time: candle.time,
        close: val,
        open: candle.open,
        low: Math.min(candle.low, val),
        high: Math.max(candle.high, val),
      });

      randomFactor = 25 + Math.random() * 1; // 重新生成随机因子
      const date = new Date(Date.UTC(2024, 0, 1, 12, 0, 0, 0)); // 设置起始日期
      const numberOfPoints = numberOfCandles * updatesPerCandle; // 计算总共需要生成的数据点数
      const initialData = []; // 初始化数据数组
      const realtimeUpdates = []; // 实时更新数据数组
      let lastCandle; // 上一个蜡烛图数据
      let previousValue = samplePoint(-1); // 上一个样本点的值
      for (let i = 0; i < numberOfPoints; ++i) {
        if (i % updatesPerCandle === 0) {
          // 根据当前区间调整日期
          switch (interval) {
            case '1D':
              date.setUTCDate(date.getUTCDate() + 1); // 每天增加1天
              break;
            case '1W':
              date.setUTCDate(date.getUTCDate() + 7); // 每周增加7天
              break;
            case '1M':
              date.setUTCMonth(date.getUTCMonth() + 1); // 每月增加1个月
              break;
            case '1Y':
              date.setUTCFullYear(date.getUTCFullYear() + 1); // 每年增加1年
              break;
          }
        }
        const time = date.getTime() / 1000; // 获取当前日期的时间戳
        let value = samplePoint(i); // 生成当前数据点的值
        const diff = (value - previousValue) * Math.random(); // 计算当前值与上一个值的差异
        value = previousValue + diff; // 更新当前值
        previousValue = value; // 更新上一个值
        if (i % updatesPerCandle === 0) {
          const candle = createCandle(value, time); // 创建蜡烛图数据
          lastCandle = candle; // 更新上一个蜡烛图数据
          if (i >= startAt) {
            realtimeUpdates.push(candle); // 如果当前数据点大于等于startAt，则将数据添加到实时更新数组
          }
        } else {
          const newCandle = updateCandle(lastCandle, value); // 更新蜡烛图数据
          lastCandle = newCandle; // 更新上一个蜡烛图数据
          if (i >= startAt) {
            realtimeUpdates.push(newCandle); // 如果当前数据点大于等于startAt，则将数据添加到实时更新数组
          } else if ((i + 1) % updatesPerCandle === 0) {
            initialData.push(newCandle); // 如果当前数据点是蜡烛图的最后一个更新，则将数据添加到初始化数据数组
          }
        }
      }

      return {
        initialData, // 返回初始化数据
        realtimeUpdates, // 返回实时更新数据
      };
    },

    // 设置图表的区间
    setData() {
      if (this.chart) {
        const data = this.generateData(2500, 20, 1000);
        this.datasource = data;
        console.log('generateData', data);
        this.series.setData(data.initialData);// 设置蜡烛图数据
        this.chart.timeScale().fitContent();// 设置图表的区间
        this.chart.timeScale().scrollToPosition(5);// 滚动到第5个数据点

        if (!this.streamingDataProvider) {
          // simulate real-time data
          function* getNextRealtimeUpdate(realtimeData) {
            for (const dataPoint of realtimeData) {
              yield dataPoint;
            }
            return null;
          }
          const streamingDataProvider = getNextRealtimeUpdate(data.realtimeUpdates);
          this.streamingDataProvider = streamingDataProvider;
          const intervalID = setInterval(() => {
            const update = streamingDataProvider.next();
            if (update.done) {
              clearInterval(intervalID);
              return;
            }
            this.series.update(update.value);
          }, 100);
        }
      }
    }
  }

}
</script>


<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;

  #container {
    width: 100%;
    border: 1px solid red;
    height: 300px;
  }
}

::v-deep #tv-attr-logo {
  display: none;
}
</style>